package com.lelefly.base.serviceImp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.lelefly.base.Validator.LeleflyUserValidator;
import com.lelefly.base.daoimp.BaseDao;
import com.lelefly.base.daoimp.LeleflyuserDao;
import com.lelefly.base.model.LeleflyUserVo;
import com.lelefly.base.model.Result;
import com.lelefly.base.model.RowResult;
import com.lelefly.base.model.UpdateIdBean;
import com.lelefly.base.model.ValidateErrors;
import com.lelefly.base.model.beidou.RegisterInfo;
import com.lelefly.base.po.LeleflyUser;
import com.lelefly.base.po.RegInfo;
import com.lelefly.base.utils.Md5Utils;
import com.lelefly.constant.Constant;
import com.lelefly.db.dbmanager.HibernateSessionFactory;
import com.lelefly.handleexecption.ServiceExecption;
import com.lelefly.handleexecption.ValidateExecption;
import com.lelefly.redis.RedisUtil;

@Service
public class LeleflyUserService extends BaseService {

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Resource
	public LeleflyuserDao leleflyuserDao;

	@Resource
	public BaseDao baseDao;

	@Resource
	public LeleflyUserValidator leleflyUserValidator;

	@Resource
	public RedisTemplate<String, String> redisTemplate;

	@Resource(name = "redisTemplate")
	public ValueOperations<String, String> valueOperations;

	@SuppressWarnings("null")
	public Result<LeleflyUserVo> getUserReUnquie(String phonenumber,
			String password) {
		Result<LeleflyUserVo> result = new Result<>();
		try {
			if (StringUtils.isEmpty(phonenumber)
					|| StringUtils.isEmpty(password)) {
				throw new ServiceExecption("参数错误");
			}
			String hql1 = "from LeleflyUser as mdeol where phonenumber='"
					+ phonenumber + "'";
			LeleflyUser leleflyUser1 = leleflyuserDao
					.getLeleflyUserReUnique(hql1);
			if (leleflyUser1 == null) {
				throw new ServiceExecption("用户名不存在");
			}
			String hql = "from LeleflyUser as mdeol where phonenumber='"
					+ phonenumber + "' and password='"
					+ Md5Utils.md5Encode(password) + "' ";
			List<LeleflyUserVo> leleflyUserVos = new ArrayList<>();
			LeleflyUser leleflyUser = leleflyuserDao
					.getLeleflyUserReUnique(hql);
			if (leleflyUser != null) {
				LeleflyUserVo leleflyUserVo = new LeleflyUserVo();
				leleflyUserVo.setUsernm(leleflyUser.getUsernm());
				leleflyUserVo.setUsername(leleflyUser.getUsername());
				leleflyUserVo.setPhonenumber(leleflyUser.getPhonenumber());
				leleflyUserVos.add(leleflyUserVo);
			} else {
				throw new ServiceExecption("密码错误");
			}
			result.setState(Constant.HTTP_STATUS_OK);
			result.setResultList(leleflyUserVos);
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		} catch (ServiceExecption e) {
			// TODO Auto-generated catch block
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		}
		return result;
	}

	@SuppressWarnings("null")
	public Result<LeleflyUserVo> getUserLoginReUnquie(String phonenumber,
			String password) {
		Result<LeleflyUserVo> result = new Result<>();
		try {
			if (StringUtils.isEmpty(phonenumber)
					|| StringUtils.isEmpty(password)) {
				throw new ServiceExecption("参数错误");
			}
			String hql1 = "from LeleflyUser as mdeol where phonenumber='"
					+ phonenumber + "'";
			LeleflyUser leleflyUser1 = leleflyuserDao
					.getLeleflyUserReUnique(hql1);
			if (leleflyUser1 == null) {
				throw new ServiceExecption("用户名不存在");
			}
			String hql = "from LeleflyUser as mdeol where phonenumber='"
					+ phonenumber + "' and password='"
					+ Md5Utils.md5Encode(password) + "' ";
			List<LeleflyUserVo> leleflyUserVos = new ArrayList<>();
			LeleflyUser leleflyUser = leleflyuserDao
					.getLeleflyUserReUnique(hql);
			if (leleflyUser != null) {
				// 判断身份证号是不是为空，必须实名认证后才能登录
				String idCard = leleflyUser.getIdcard();

				if (StringUtils.isEmpty(idCard)) {
					result.setState(Constant.HTTP_ID_CARD_IS_NULL);
					result.setMes("当前账号未进行实名认证");
					return result;
				}
				LeleflyUserVo leleflyUserVo = new LeleflyUserVo();
				leleflyUserVo.setUsernm(leleflyUser.getUsernm());
				leleflyUserVo.setUsername(leleflyUser.getUsername());
				leleflyUserVo.setPhonenumber(leleflyUser.getPhonenumber());
				leleflyUserVos.add(leleflyUserVo);
			} else {
				throw new ServiceExecption("密码错误");
			}
			result.setState(Constant.HTTP_STATUS_OK);
			result.setResultList(leleflyUserVos);
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		} catch (ServiceExecption e) {
			// TODO Auto-generated catch block
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		}
		return result;
	}

	/**
	 * 更新身份证号码
	 * 
	 * @param bean
	 * @return
	 */
	public Result<LeleflyUser> updateUserCardNo(UpdateIdBean bean) {
		Result<LeleflyUser> result = new Result<>();
		if (StringUtils.isEmpty(bean.getPhonenumber())
				|| StringUtils.isEmpty(bean.getPassword())
				|| StringUtils.isEmpty(bean.getIdcard())) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("参数错误");
			return result;
		}
		try {
			String phonenumber = bean.getPhonenumber();
			String password = bean.getPassword();
			String idNo = bean.getIdcard();
			String hql1 = "from LeleflyUser as mdeol where phonenumber='"
					+ phonenumber + "'";
			LeleflyUser leleflyUser1 = leleflyuserDao
					.getLeleflyUserReUnique(hql1);
			if (leleflyUser1 == null) {
				throw new ServiceExecption("用户名不存在");
			}
			String hql = "from LeleflyUser as mdeol where phonenumber='"
					+ phonenumber + "' and password='"
					+ Md5Utils.md5Encode(password) + "' ";
			List<LeleflyUserVo> leleflyUserVos = new ArrayList<>();
			LeleflyUser leleflyUser = leleflyuserDao
					.getLeleflyUserReUnique(hql);
			if (leleflyUser != null) {
				// 更新身份证号码
				// String updateHql = "update LeleflyUser set idcard='" + idNo +
				// "' "
				// + "where phonenumber='" + phonenumber + "'";
				leleflyUser.setIdcard(idNo);
				leleflyuserDao.saveOrUpdateObject(leleflyUser);
				result.setState(Constant.HTTP_STATUS_OK);
				result.setMes("更新身份证号码成功");
				List<LeleflyUser> list = new ArrayList<>();
				list.add(leleflyUser);
				result.setResultList(list);
			} else {
				throw new ServiceException("密码错误");
			}
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("服务器异常");
		} catch (ServiceExecption e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		}

		return result;
	}

	@SuppressWarnings("null")
	public Result<LeleflyUser> getUserReUnquieAndAllField(String usernm) {
		Result<LeleflyUser> result = new Result<>();
		try {
			if (StringUtils.isEmpty(usernm)) {
				throw new ServiceExecption("参数错误");
			}
			String hql = "select LeleflyUser as mdeol where usernm='" + usernm
					+ "' ";
			List<LeleflyUser> leleflyUsers = leleflyuserDao
					.queryObjetReList(hql);
			result.setState(Constant.HTTP_STATUS_OK);
			result.setResultList(leleflyUsers);
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		} catch (ServiceExecption e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		}
		return result;
	}

	public LeleflyUser getUser(String phoneNum, String pwd) {
		LeleflyUser user = null;
		try {
			String hql = "from LeleflyUser as mdeol where phonenumber='"
					+ phoneNum + "' and password='" + Md5Utils.md5Encode(pwd)
					+ "' ";
			user = (LeleflyUser) leleflyuserDao.getObjcetReUnique(hql);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	public String cacheLoginInfo(String phoneNum) {
		String token = UUID.randomUUID().toString().replaceAll("-", "");
		valueOperations.setIfAbsent(token, phoneNum);
		redisTemplate
				.expire(token, Constant.TOKEN_EXPIRETIME, TimeUnit.SECONDS);

		return token;
	}

	/**
	 * 根据token获取账号信息
	 * 
	 * @param token
	 * @return
	 */
	public String getPhoneNumByToken(String token) {

		return valueOperations.get(token);
	}

	@SuppressWarnings({ "null", "unused" })
	public Result<LeleflyUserVo> addLeleflyUser(LeleflyUser leleflyUser,
			String code) {
		Result<LeleflyUserVo> result = new Result<>();
		try {
			ValidateErrors validateErrors = new ValidateErrors();
			leleflyUserValidator.validator(leleflyUser, validateErrors);
			if (validateErrors.isHasError()) {
				throw new ValidateExecption(validateErrors.getStackFirstError());
			}
			String sql = "from LeleflyUser as model where phonenumber ='"
					+ leleflyUser.getPhonenumber() + "'";
			LeleflyUser user = leleflyuserDao.getLeleflyUserReUnique(sql);
			if (user != null) {
				throw new ValidateExecption("该手机号已注册");
			}
			if (StringUtils.isEmpty(code)) {
				throw new ServiceExecption("参数为空");
			}
			String hql = "from RegInfo as mdoel where tel='"
					+ leleflyUser.getPhonenumber() + "'";
			RegInfo regInfo = (RegInfo) baseDao.getObjcetReUnique(hql);
			if (System.currentTimeMillis()
					- Long.valueOf(regInfo.getExpiredTime()) >= 1000 * 60 * 30) {
				throw new ServiceExecption("验证码已过期");
			}
			if (regInfo == null) {
				throw new ServiceExecption("请输入合法验证码");
			}
			if (!regInfo.getRegCode().equals(code)) {
				throw new ServiceExecption("验证码输入错误");
			}
			List<LeleflyUserVo> leleflyUserVos = new ArrayList<>();
			leleflyUser.setPassword(Md5Utils.md5Encode(leleflyUser
					.getPassword()));
			leleflyUser.setRegisterDate(sdf.format(new Date()));
			if (StringUtils.equals(leleflyUser.getIsunit(), Constant.IS_UNIT)) {// 飞防队账户注册
				// 飞防队注册要同时注册组织
				leleflyuserDao.saveOrganizationUser(leleflyUser);
			} else if (StringUtils.equals(leleflyUser.getIsunit(),
					Constant.IS_PERSONAL)) {// 个人账户注册
				leleflyuserDao.saveObject(leleflyUser);
			}
			result.setState(Constant.HTTP_STATUS_OK);
			if (leleflyUser != null) {
				LeleflyUserVo leleflyUserVo = new LeleflyUserVo();
				leleflyUserVo.setUsernm(leleflyUser.getUsernm());
				leleflyUserVo.setUsername(leleflyUser.getUsername());
				leleflyUserVo.setPhonenumber(leleflyUser.getPhonenumber());
				leleflyUserVos.add(leleflyUserVo);
			}
			result.setResultList(leleflyUserVos);
		} catch (Exception e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		} catch (ValidateExecption e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		} catch (ServiceExecption e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		}
		return result;
	}

	@SuppressWarnings({ "null", "unused" })
	public Result<LeleflyUserVo> resetLeleflyUser(LeleflyUser leleflyUser,
			String code) {
		Result<LeleflyUserVo> result = new Result<>();
		try {
			ValidateErrors validateErrors = new ValidateErrors();
			leleflyUserValidator.validator(leleflyUser, validateErrors);
			if (validateErrors.isHasError()) {
				throw new ValidateExecption(validateErrors.getStackFirstError());
			}
			String sql = "from LeleflyUser as model where phonenumber ='"
					+ leleflyUser.getPhonenumber() + "'";
			LeleflyUser user = leleflyuserDao.getLeleflyUserReUnique(sql);
			if (user == null) {
				throw new ValidateExecption("该手机号未注册");
			}
			if (StringUtils.isEmpty(code)) {
				throw new ServiceExecption("验证码为空");
			}
			String hql = "from RegInfo as mdoel where tel='"
					+ leleflyUser.getPhonenumber() + "'";
			RegInfo regInfo = (RegInfo) baseDao.getObjcetReUnique(hql);
			if (System.currentTimeMillis()
					- Long.valueOf(regInfo.getExpiredTime()) >= 1000 * 60 * 30) {
				throw new ServiceExecption("验证码已过期");
			}
			if (regInfo == null) {
				throw new ServiceExecption("请输入合法验证码");
			}
			if (!regInfo.getRegCode().equals(code)) {
				throw new ServiceExecption("验证码输入错误");
			}
			List<LeleflyUserVo> leleflyUserVos = new ArrayList<>();
			user.setPassword(Md5Utils.md5Encode(leleflyUser.getPassword()));
			leleflyuserDao.UpdateObject(user);
			result.setState(Constant.HTTP_STATUS_OK);
			if (leleflyUser != null) {
				LeleflyUserVo leleflyUserVo = new LeleflyUserVo();
				leleflyUserVo.setUsernm(user.getUsernm());
				leleflyUserVo.setUsername(user.getUsername());
				leleflyUserVo.setPhonenumber(user.getPhonenumber());
				leleflyUserVos.add(leleflyUserVo);
			}
			result.setResultList(leleflyUserVos);
		} catch (Exception e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		} catch (ValidateExecption e) {
			// TODO Auto-generated catch block
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		} catch (ServiceExecption e) {
			// TODO Auto-generated catch block
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		}
		return result;
	}

	@SuppressWarnings("null")
	public Result<LeleflyUserVo> updateLeleflyUser(LeleflyUser leleflyUser) {
		Result<LeleflyUserVo> result = new Result<>();
		try {
			// ValidateErrors validateErrors = new ValidateErrors();
			// leleflyUserValidator.validator(leleflyUser, validateErrors);
			// if (validateErrors.isHasError()) {
			// throw new ValidateExecption(validateErrors.getStackFirstError());
			// }
			leleflyuserDao.UpdateObject(leleflyUser);
			result.setState(Constant.HTTP_STATUS_OK);
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		}
		return result;
	}

	@SuppressWarnings("null")
	public Result<LeleflyUser> delLeleflyUser(String usernm) {
		Result<LeleflyUser> result = new Result<>();
		try {
			if (StringUtils.isEmpty(usernm)) {
				throw new ServiceExecption("删除条件为空");
			}
			String sql = "detele LeleflyUser as model where usernm='" + usernm
					+ "' ";
			leleflyuserDao.deteleObjectbySql(sql);
			result.setState(Constant.HTTP_STATUS_OK);
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		} catch (ServiceExecption e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		}
		return result;
	}

	public RowResult<LeleflyUser> getAllUser(String start, String limit) {
		RowResult<LeleflyUser> result = new RowResult<>();

		try {
			if (StringUtils.isEmpty(start)) {
				start = "0";
			}
			if (StringUtils.isEmpty(limit)) {
				limit = "20";
			}
			SessionFactory sessionFactory = HibernateSessionFactory
					.getSessionFactory();
			Session session = sessionFactory.openSession();
			String hql = "from LeleflyUser";
			Query query = session.createQuery(hql);
			int page = Integer.valueOf(start);
			int count = Integer.valueOf(limit);
			query.setFirstResult(page);
			query.setMaxResults(count);
			List<LeleflyUser> list = query.list();
			result.setTotal(baseDao.queryObjetReList(hql).size());
			result.setRows(list);
			return result;
		} catch (Exception e) {

		}
		return result;
	}
}
